package com.autogo

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.GestureDescription
import android.graphics.Path
import android.view.accessibility.AccessibilityEvent
import android.widget.Toast

/**
 * AutoGo 无障碍服务
 * 用于执行后台自动点击、滑动等操作。
 */
class AutoGoAccessibilityService : AccessibilityService() {

    /**
     * 系统连接到无障碍服务时调用
     * 此处注册当前实例，让原生模块可访问
     */
    override fun onServiceConnected() {
        super.onServiceConnected()
        AutoGoServiceHolder.serviceInstance = this
        Toast.makeText(this, "✅ AutoGo 无障碍服务已连接", Toast.LENGTH_SHORT).show()
    }

    /**
     * 服务销毁时清除引用，防止内存泄漏
     */
    override fun onDestroy() {
        super.onDestroy()
        AutoGoServiceHolder.serviceInstance = null
        Toast.makeText(this, "❌ AutoGo 无障碍服务已断开", Toast.LENGTH_SHORT).show()
    }

    /**
     * 监听无障碍事件（这里暂时不处理）
     */
    override fun onAccessibilityEvent(event: AccessibilityEvent?) {}

    /**
     * 服务被系统打断（如无障碍被关闭）
     */
    override fun onInterrupt() {}

    // -------------------------------
    // 以下是暴露给 React Native 模块可调用的动作
    // -------------------------------

    /** 模拟上滑或下滑操作 */
    fun performSwipe(direction: String) {
        val path = Path()
        when (direction) {
            "up" -> { // 向上滑
                path.moveTo(500f, 1500f)
                path.lineTo(500f, 500f)
            }
            "down" -> { // 向下滑
                path.moveTo(500f, 500f)
                path.lineTo(500f, 1500f)
            }
            else -> {
                showToast("未知滑动方向：$direction")
                return
            }
        }

        val gesture = GestureDescription.Builder()
            .addStroke(GestureDescription.StrokeDescription(path, 0, 500))
            .build()

        dispatchGesture(gesture, null, null)
    }

    /** 模拟点击操作 */
    fun performClick(x: Float, y: Float) {
        val path = Path()
        path.moveTo(x, y)
        val gesture = GestureDescription.Builder()
            .addStroke(GestureDescription.StrokeDescription(path, 0, 100))
            .build()

        dispatchGesture(gesture, null, null)
    }

    /** 快捷提示 */
    fun showToast(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }
}

/**
 * 全局单例：保存当前无障碍服务实例
 * 供 AutoGoModule 从 React Native 层访问。
 */
object AutoGoServiceHolder {
    var serviceInstance: AutoGoAccessibilityService? = null
}
